﻿using IdentityServer4.Stores;
using Lk.Common.Helper;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using OAuth.Dapper;
using OAuth.Dapper.Infrastructure.Data;
using OAuth.Server.Domain;
using OAuth.Server.OAuth;
using System.Security.Cryptography;

namespace OAuth.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDapperDBContext<MySQLDbConfig>(options =>
            {
                options.Configuration = ConfigHelper.GetSection("ConnectionStrings", "MySqlServerConnection");
                options.DbType = ConfigHelper.GetSection("ConnectionStrings", "DbType");
            });
            services.AddTransient<IAccountRepository, UowAccountRepository>();

            services.AddTransient<IClientStore, ClientStore>();
            //services.AddTransient<IResourceStore, ResourceStore>();
            //  services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();

            //RSA：证书长度2048以上，否则抛异常
            //配置AccessToken的加密证书
            var rsa = new RSACryptoServiceProvider();
            //从配置文件获取加密证书
            //  rsa.ImportCspBlob(Convert.FromBase64String(Configuration["SigningCredential"]));
            ////配置IdentityServer4
            //services.AddSingleton<IClientStore, MyClientStore>();   //注入IClientStore的实现，可用于运行时校验Client的配置
            //services.AddSingleton<IScopeStore, MyScopeStore>();    //注入IScopeStore的实现，可用于运行时校验Scope的配置
            ////注入IPersistedGrantStore的实现，用于存储AuthorizationCode和RefreshToken等等，默认实现是存储在内存中，
            ////如果服务重启那么这些数据就会被清空了，因此实现IPersistedGrantStore将这些数据写入到数据库或者NoSql(Redis)中
            //services.AddSingleton<IPersistedGrantStore, MyPersistedGrantStore>();
            services.AddIdentityServer()
                .AddSigningCredential(new RsaSecurityKey(rsa))
            .AddResourceOwnerValidator<OwnerValidator>()   //生成临时的加密证书，每次重启服务都会重新生成
            .AddProfileService<ProfileService>();    //将Scopes设置到内存中
            //.AddInMemoryClients(Config.GetClients())    //将Clients设置到内存中

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();
            //services.AddTransient<IAccountRepository, AccountRepository>();
            services.AddMvc();


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            //loggerFactory.AddProvider(new ColoredConsoleLoggerProvider(new ColoredConsoleLoggerConfiguration() { Color = ConsoleColor.Blue, LogLevel = LogLevel.Information }));
            // loggerFactory.AddProvider(new ColoredConsoleLoggerProvider(new ColoredConsoleLoggerConfiguration() { Color = ConsoleColor.Red, LogLevel = LogLevel.Error }));
            // loggerFactory.AddProvider(new ColoredConsoleLoggerProvider(new ColoredConsoleLoggerConfiguration() { Color = ConsoleColor.Gray, LogLevel = LogLevel.Debug }));
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            app.UseHttpsRedirection();


            // app.UseApplicationInsightsRequestTelemetry();
            //  app.UseApplicationInsightsExceptionTelemetry();

            //使用IdentityServer4
            // app.UseIdentityServer();

            //使用Cookie模块  2.x 代替  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie();
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
            //    AutomaticAuthenticate = false,
            //    AutomaticChallenge = false
            //});


            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute("areaRoute", "{area:exists}/{controller}/{action=index}/{id?}");
            });
        }
    }
}
